package com.huice.base;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class ExcelParser {

	private Workbook workbook = null;
	
	public ExcelParser(String filaName){
		try {
			workbook = new HSSFWorkbook(new FileInputStream(filaName));
		} catch (Exception e) {
			try {
				workbook = new XSSFWorkbook(new FileInputStream(filaName));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
		}
	}
	
	public String getValue(String sheetName, int x, int y){	
		Sheet sheet = workbook.getSheet(sheetName);
		return sheet.getRow(x).getCell(y).getStringCellValue();
	}
	
	public List<Map<String, String>> getData(String sheetName){
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		Sheet sheet = workbook.getSheet(sheetName);
		int rownumber = sheet.getLastRowNum();

		for(int i=1;i<rownumber+1;i++){
			Map<String, String> map = new LinkedHashMap<String,String>();
			Row row = sheet.getRow(i);
			int Column = row.getPhysicalNumberOfCells();
				for(int j=0;j<Column;j++){
					Cell valueCell = row.getCell(j);
					Cell keyCell = sheet.getRow(0).getCell(j);
					valueCell.setCellType(Cell.CELL_TYPE_STRING);
					valueCell.setCellType(Cell.CELL_TYPE_STRING);
					map.put(keyCell.getStringCellValue(), 
							valueCell.getStringCellValue());
				}
			data.add(map);
		}
		return data;
	}
	
}
